//
//  MyMapViewController.m
//  CivilianTravel
//
//  Created by xalo on 16/7/22.
//  Copyright © 2016年 许仕杰. All rights reserved.
//

#import "MyMapViewController.h"
#import <AMapSearchKit/AMapSearchAPI.h>
#import <CoreLocation/CoreLocation.h>

@interface MyMapViewController ()<MAMapViewDelegate,AMapSearchDelegate,UITextFieldDelegate,
CLLocationManagerDelegate>

@property (weak, nonatomic) IBOutlet UILabel *timeLable;  //时间

@property (weak, nonatomic) IBOutlet UILabel *speedLabe;    //  速度

@property (weak, nonatomic) IBOutlet UILabel *spaceLable;  // 距离

@property (weak, nonatomic) IBOutlet UILabel *AllTimeLable;  // 总时间

@property (weak, nonatomic) IBOutlet UILabel *averageLable;  //  平均速度
@property (weak, nonatomic) IBOutlet UILabel *alwaysjourneylable;   //总路程








@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property(nonatomic,strong)MAMapView *mapView;
@property (weak, nonatomic) IBOutlet UIView *Myview;

@property (weak, nonatomic) IBOutlet UILabel *label;

@property (weak, nonatomic) IBOutlet UILabel *locationcity;



@property(nonatomic,strong)AMapSearchAPI *search;

@property(nonatomic,strong)NSMutableArray *dataArray;

@property(nonatomic,strong)CLLocationManager *locationManager;
@property(nonatomic,readonly)CLLocationDistance altitudinate;  // 海拔
@property(nonatomic,readonly)CLLocationSpeed speed;// //行走速度（单位是m/s）

@property(readonly, nonatomic) CLLocationDirection course;
//路线，航向（取值范围是0.0&deg; ~ 359.9&deg;，0.0&deg;代表真北方向）


// 上一次的位置
@property (nonatomic, strong) CLLocation *previousLocation;
// 总路程
@property (nonatomic, assign) CLLocationDistance  sumDistance;
// 总时间
@property (nonatomic, assign) NSTimeInterval  sumTime;


@property(readonly, nonatomic, copy) CLFloor *floor ;

//CLFloor中的一个属性，显示低第几层楼
@property(readonly, nonatomic) NSInteger level;

@property(nonatomic,strong)CLLocation *curLocation;


@end


@implementation MyMapViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    

    [self createMapView];  // 调用地图
    
    [self.Myview insertSubview:self.mapView atIndex:0];  // 把地图放在底层
  
    
    _locationManager = [[CLLocationManager alloc]init];
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    _locationManager.delegate = self;
    [_locationManager requestAlwaysAuthorization];
    [_locationManager startUpdatingLocation];
    
  
    
    
}




// 地图基本设置

-(void)createMapView {
    self.mapView = [[MAMapView alloc]initWithFrame:CGRectMake(0, 0, self.Myview.frame.size.width, self.Myview.frame.size.height)];
    
    self.mapView.delegate = self;
    self.mapView.showsLabels = YES;  //显示底层标注
    self.mapView.mapType = MAMapTypeStandard; //   地图类型
//    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = 1;
    //  比例尺
    self.mapView.compassOrigin = CGPointMake(self.mapView.compassOrigin.x, 22);
    
    self.mapView.scaleOrigin = CGPointMake(self.mapView.scaleOrigin.x, 22);
    self.mapView.touchPOIEnabled = YES;
    
    [self.mapView setUserTrackingMode: MAUserTrackingModeFollow animated:YES];  // 地图跟着位置移动
    
}




//  显示位置
-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation
updatingLocation:(BOOL)updatingLocation
{
    if(updatingLocation)
    {
        //  地理编码  显示具体位置
        CLGeocoder *geocoder = [[CLGeocoder alloc]init];
        [geocoder reverseGeocodeLocation:userLocation.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            
            CLPlacemark *make = placemarks.firstObject;
    
            self.locationcity.text = make.name;
            

                      
        }];
        
    }
}

// 当前海拔
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    self.curLocation = [locations lastObject];
    
    if(self.curLocation.horizontalAccuracy > 0)
    {
//        NSLog(@"当前位置：%.0f,%.0f +/- %.0f meters",self.curLocation.coordinate.longitude,
//              self.curLocation.coordinate.latitude,
//              self.curLocation.horizontalAccuracy);
    }
    
    if(self.curLocation.verticalAccuracy > 0)
    {
//        NSLog(@"当前海拔高度：%.0f +/- %.0f meters",self.curLocation.altitude,self.curLocation.verticalAccuracy);
        self.label.text = [NSString stringWithFormat:@"%.0f ",self.curLocation.altitude];
     
    }
    if (self.previousLocation != nil) {
        // 计算两次的距离(单位时米)
        CLLocationDistance distance = [self.curLocation distanceFromLocation:self.previousLocation];
        // 计算两次之间的时间（单位只秒）
        NSTimeInterval dTime = [self.curLocation.timestamp timeIntervalSinceDate:self.previousLocation.timestamp];
        // 计算速度（米／秒）
        CGFloat speed = distance / dTime;
        
        
        // 累加时间
        self.sumTime += dTime;
        
        // 累加距离
        self.sumDistance += distance;
        
        //  计算平均速度
        CGFloat avgSpeed = self.sumDistance / self.sumTime;
        
//        NSLog(@"距离%f 时间%f 速度%f 平均速度%f 总路程 %f 总时间 %f", distance, dTime, speed, avgSpeed, self.sumDistance, self.sumTime);
   
        
        self.timeLable.text = [NSString stringWithFormat:@"%f",dTime];
        self.speedLabe.text = [NSString stringWithFormat:@"%f",speed];
        self.spaceLable.text = [NSString stringWithFormat:@"%f",distance];
        self.AllTimeLable.text = [NSString stringWithFormat:@"%f",self.sumTime];
        self.averageLable.text = [NSString stringWithFormat:@"%f",avgSpeed];
        self.alwaysjourneylable.text = [NSString stringWithFormat:@"%f",self.sumDistance];
        
        
    }
    
    // 纪录上一次的位置
    self.previousLocation = self.curLocation;
    
    

    
    
}


- (IBAction)mapbutton:(id)sender {
    
      [self.scrollView setContentOffset:CGPointZero animated:YES];
}


- (IBAction)curbutton:(id)sender {
    
        [self.scrollView setContentOffset:CGPointMake(kWidth, 0) animated:YES];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
